<?php
/**
 * 上传平台国家
 * User: bgl
 * Date: 2022/9/19
 * Time: 14:40
 */

namespace App\Admin\Controllers\Basics;

use App\Importer\Basics\BImporter;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlatCountry;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class SysPlatCountryUploadController extends AdminController{

    protected $title = '上传平台收货国家';

    protected function grid(){

        return view("basics.sys-plat-receiver-country.index");
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $re = $this->_importFile($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importFile(UploadedFile $file){

        try{
            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            foreach($data as $row){
                $count++;
                $_countryCn = $row[0] ? trim($row[0]) : '';
                $_countryCode = $row[1] ? trim($row[1]) : '';
                $_mathcCountryCode = $row[2] ? trim($row[2]) : '';
                if(!$_countryCn || !$_countryCode || !$_mathcCountryCode){
                    $errors[$count] = '必填项不能为空';
                    continue;
                }
                $countryCode = strtoupper($_countryCode); //字符串转换大写
                $countryCount = SysPlatCountry::query()->where(['country_code'=>$countryCode])->count();
                if($countryCount > 0){
                    $errors[$count] = $_countryCode.'系统已存在该收货国家编码';
                    continue;
                }
                $mathcCountryCode = strtoupper($_mathcCountryCode); //字符串转换大写
                $mathcCountryId = SysCountry::getIdByCountry($mathcCountryCode);
                if(!$mathcCountryId){
                    $errors[$count] = $_mathcCountryCode.'系统不存在该映射国家编码';
                    continue;
                }
                //创建平台收货国家
                DB::beginTransaction();
                SysPlatCountry::query()->updateOrCreate(
                    [
                        'country_code' => $countryCode
                    ],
                    [
                        'country_cn' => $_countryCn,
                        'country_id' => $mathcCountryId,
                    ]);
                DB::commit();
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }

}
